/**
 * 路由守卫配置
 * 处理路由权限控制、登录验证等
 */
import { useAuthStore } from '@/stores/auth'
import { ElMessage } from 'element-plus'

// 路由白名单
const whiteList = ['/login', '/register']

// 角色路由映射
const roleRouteMap = {
  student: '/student',
  teacher: '/teacher',
  admin: '/admin'
}

// 检查考试权限
async function checkExamPermission(examId) {
  try {
    const response = await fetch(`/api/exam/${examId}/permission`)
    const data = await response.json()
    return data.canEnter
  } catch (error) {
    console.error('检查考试权限失败:', error)
    return false
  }
}

export function setupRouteGuard(router) {
  router.beforeEach(async (to, from, next) => {
    const authStore = useAuthStore()

    // 白名单直接放行
    if (whiteList.includes(to.path)) {
      next()
      return
    }

    // 检查是否登录
    if (!authStore.isAuthenticated) {
      ElMessage.warning('请先登录')
      next('/login')
      return
    }

    // 检查路由权限
    if (to.meta.role && to.meta.role !== authStore.userRole) {
      ElMessage.error('无权访问该页面')
      next(from.path)
      return
    }

    // 访问根路径时重定向到对应角色首页
    if (to.path === '/') {
      const redirectPath = roleRouteMap[authStore.userRole]
      if (redirectPath) {
        next(redirectPath)
        return
      }
    }

    // 检查考试权限
    if (to.name === 'StudentExam') {
      const examId = to.params.id
      try {
        // 检查考试状态和权限
        const canEnterExam = await checkExamPermission(examId)
        if (!canEnterExam) {
          ElMessage.error('无法进入该考试')
          next(from.path)
          return
        }
      } catch (error) {
        console.error('检查考试权限失败:', error)
        ElMessage.error('检查考试权限失败')
        next(from.path)
        return
      }
    }

    next()
  })

  // 路由错误处理
  router.onError((error) => {
    console.error('路由错误:', error)
    ElMessage.error('页面加载失败')
  })
} 